import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  permission: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
 
  // 用户登录
  login({ commit }, userInfo) {
    // 从userinfo里面取出username 和password
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { Authorization } = response
        commit('SET_TOKEN', Authorization)
        setToken(Authorization)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { roles, username, permissions,picture } = response

        if (!username) {
          reject('用户身份过期,请登录!')
        }
        commit('SET_ROLES', roles)//用户角色
        commit('SET_NAME', username)//用户名称
        commit('SET_AVATAR', picture)//用户头像
        commit('SET_PERMISSION', permissions)//用户权限 
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  //退出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
      
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        commit('SET_ROLES', [])
        commit('SET_AVATAR', '')//用户头像
        commit('SET_PERMISSION', [])
        removeToken()
        resetRouter() //重置路由
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSION', [])
      removeToken()
      resolve()
    })
  },

 
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
